const path = require("path");
const fs = require("fs");
const { BundleAnalyzerPlugin } = require("webpack-bundle-analyzer");
// const StyleLintPlugin = require('stylelint-webpack-plugin')
const WebpackBar = require("webpackbar");

const PROXY_JS = "proxy.js";
const PROXY_JS_BAK = "proxy.js.bak";

function resolve(dir) {
  return path.join(__dirname, dir);
}

let proxy;

try {
  // eslint-disable-next-line import/no-dynamic-require
  proxy = require(`./${PROXY_JS}`);
} catch {
  proxy = null;
}

if (!proxy) {
  try {
    fs.statSync(resolve(`./${PROXY_JS_BAK}`));
    fs.copyFileSync(resolve(`./${PROXY_JS_BAK}`), resolve(`./${PROXY_JS}`));
    const vm = require("vm");
    const context = vm.createContext({
      module,
    });
    proxy = vm.runInContext(
      fs.readFileSync(resolve(`./${PROXY_JS}`), {
        encoding: "utf-8",
      }),
      context
    );
  } catch (error) {
    console.log(error);
    console.error(`请提供 proxy.js 或 proxy.js.bak 文件`);
    process.exit(-1);
  }
}

const IS_PROD = process.env.NODE_ENV === "production";
const PROJECT_NAME = "warning-config-center";
const publicPath = IS_PROD ? "./" : "./";
process.env.VUE_APP_PUBLIC_PATH = publicPath;
process.env.VUE_APP_PROJECT_NAME = PROJECT_NAME;

module.exports = {
  pluginOptions: {
    dll: {
      // 入口配置
      entry: [
        "vue",
        "vuex",
        "vue-router",
        "vxe-table",
        "esri-loader",
        "vuedraggable",
        "vue-resource",
        "lodash-es",
        "element-ui",
        "core-js",
        "echarts",
      ],
      // 输出目录
      output: path.join(__dirname, "./public/dll"),

      // 是否开启 DllReferencePlugin,
      open: true,

      // 在执行 `dev` , `build` 等其他指令时，程序会自动将 `dll` 指令生成的 `*.dll.js` 等文件自动注入到 index.html 中。
      inject: true,
    },
  },
  pages: {
    index: {
      entry: "src/main.js",
    },
  },

  chainWebpack: (config) => {
    config.resolve.alias
      .set("@", resolve("src"))
      .set("assets", resolve("src/assets"));
    // config.plugin('stylelint').use(StyleLintPlugin, [
    //     {
    //         cache: true,
    //         files: ['**/*.{vue,css,scss}'],
    //     },
    // ])
    config.plugin("webpackbar").use(WebpackBar);
    // TODO: 升级到 webpack 5 之后，用 eslint-webpack-plugin 替代
    // config.module
    //     .rule('eslint')
    //     .pre()
    //     .exclude.add(/node_modules/)
    //     .add(path.dirname(require.resolve('@vue/cli-service')))
    //     .end()
    //     .test(/\.(vue|(j|t)sx?)$/)
    //     .use('eslint-loader')
    //     .loader(require.resolve('eslint-loader'))
    //     .options({
    //         cache: true,
    //         emitWarning: !IS_PROD,
    //         emitError: !IS_PROD,
    //         cacheDirectory: true,
    //         exclude: !IS_PROD ? /public/ : ''
    //     })
    config.module.rules.delete("svg");
    config.module
      .rule("icons")
      .test(/\.svg$/)
      .include.add(resolve("src/views/risk/icons"))
      .end()
      .use("svg-sprite-loader")
      .loader("svg-sprite-loader")
      .options({
        symbolId: "icon-[name]",
      })
      .end();

    // config.module
    //     .rule('worker')
    //     .test(/\.worker\.js$/)
    //     .use('worker')
    //     .loader('worker-loader')
    //     .options({
    //
    //         inline: 'fallback'
    //     })
    // config.module.rule("js").exclude.add(/\.worker\.js$/)
    if (IS_PROD) {
      config.plugin("analyze").use(BundleAnalyzerPlugin, [
        {
          analyzerMode: "static",
          generateStatsFile: true,
          openAnalyzer: false,
          reportFilename: "../stats/report.html", // 相对于 dist 文件夹
          statsFilename: "../stats/stats.json",
        },
      ]);
    }
  },

  configureWebpack: (config) => {
    config.module.rules
      .filter((rule) => rule.test.toString().includes("scss"))
      .forEach((rule) => {
        rule.oneOf.forEach((oneOfRule) => {
          oneOfRule.use.splice(
            oneOfRule.use.indexOf(require.resolve("sass-loader")),
            0,
            { loader: require.resolve("css-unicode-loader") }
          );
        });
      });
  },

  css: {
    loaderOptions: {
      // sass: {
      //     additionalData: `
      //         @import "~@yiducloud/theme-yidu/common/var.scss"
      //         @import "~@/style/_global-variables.scss"
      //         @import "~@/style/methods.scss"
      //     `,
      // },
      // scss: {
      //     additionalData: `
      //         @import "~@yiducloud/theme-yidu/common/var.scss";
      //         @import "~@/style/_global-variables.scss";
      //         @import "~@/style/methods.scss";
      //     `,
      // },
      sass: {
        additionalData: `
                    @import "~@/style/_global-variables.scss"
                    @import "~@/style/methods.scss"
                `,
      },
      scss: {
        additionalData: `
                    @import "~@/style/_global-variables.scss";
                    @import "~@/style/methods.scss";
                `,
      },
    },
  },

  devServer: {
    port: 9003,
    hot: true,
    disableHostCheck: true,
    overlay: {
      warnings: false,
      errors: true,
    },
    historyApiFallback: {
      // history模式的路由回退配置
      // verbose: true, // 打印日志
      rewrites: [
        {
          from: /(.*)\/(css|js|data|fonts|images|img)\/(.*)/,
          to(context) {
            return context.parsedUrl.pathname.replace(
              /(.*)\/(css|js|data|fonts|images|img)\/(.*)/,
              "/$2/$3"
            );
          },
        },
      ],
    },
    proxy,
  },
  publicPath,
  runtimeCompiler: true,
  productionSourceMap: false,
  lintOnSave: false,
  transpileDependencies: [/@yiducloud/],
};
